package leecode

import (
	"container/list"
	"sort"
)

func kthSmallest(root *TreeNode, k int) int {
	if root == nil {
		return 0
	}
	queue := list.New()
	queue.PushBack(root.Val)
	var resultArr []int
	for queue.Len() != 0 {
		size := queue.Len()
		temp := make([]int, 0)
		for i := 0; i < size; i++ {
			node := queue.Remove(queue.Front()).(*TreeNode)
			if node.Left != nil {
				queue.PushBack(node.Left)
			}
			if node.Right != nil {
				queue.PushBack(node.Right)
			}
			temp = append(temp, node.Val)
		}
		resultArr = append(resultArr, temp...)
	}
	sort.Ints(resultArr)
	return resultArr[k-1]
}
